﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using Simp.CodeModel;
using System.Collections.Specialized;

namespace Simp.Interpreter
{
	/// <summary>Output of simplified <c>Simp</c> functions.</summary>
	public partial class TextOutputUserControl : UserControl
	{
		/// <summary>Constructor.</summary>
		public TextOutputUserControl()
		{
			InitializeComponent();
		}

		#region ContentItemList Property
		private static readonly DependencyProperty ContentItemListProperty = DependencyProperty.Register(
			"ContentItemList",
			typeof(ObservableCollection<IContentItem>),
			typeof(TextOutputUserControl),
			new UIPropertyMetadata(new ObservableCollection<IContentItem>(), OnContentItemListChanged));

		/// <summary>List of <see cref="IContentItem"/>.</summary>
		public ObservableCollection<IContentItem> ContentItemList
		{
			get { return (ObservableCollection<IContentItem>)GetValue(ContentItemListProperty); }
			set { SetValue(ContentItemListProperty, value); }
		}
		#endregion

		private static void OnContentItemListChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			TextOutputUserControl textOutputUserControl = (TextOutputUserControl)d;
			INotifyCollectionChanged oldCollection = (INotifyCollectionChanged)e.OldValue;
			INotifyCollectionChanged newCollection = (INotifyCollectionChanged)e.NewValue;

			if (oldCollection != null)
			{
				oldCollection.CollectionChanged -= textOutputUserControl.OnCollectionChanged;
			}
			if (newCollection != null)
			{
				newCollection.CollectionChanged += textOutputUserControl.OnCollectionChanged;
			}
		}

		private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (e.Action == NotifyCollectionChangedAction.Add)
			{
				scrollViewer.ScrollToEnd();
			}
		}
	}
}